<template>
    <div>
        <br/>
        <p style="font-size: xx-large; margin-left: 400px;">新建帖子</p>
        <br/>
        <a-form
            :model="formState"
            name="basic"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
            autocomplete="off"
            @finish="onFinish"
            style="width: 1000px;"
        >
            <a-form-item
                label="标题"
                name="topic"
                :rules="[{ required: true, message: '请输入标题' }]"
            >
                <a-input v-model:value="formState.topic" />
            </a-form-item>

            <a-form-item
                label="内容"
                name="content"
                :rules="[{ required: true, message: '请输入内容' }]"
            >
                <a-textarea v-model:value="formState.content" />
            </a-form-item>

            <a-form-item label="图片" name="图片">
                <a-upload
                    v-model:file-list="fileList"
                    list-type="picture-card"
                    :max-count="10"
                    @preview="handlePreview"
                    :before-upload="beforeUploadPic"
                    :customRequest="handleUpload"
                    @remove="handleRemove"
                >
                    <div>
                        <plus-outlined />
                        <div style="margin-top: 8px">Upload</div>
                    </div>
                </a-upload>
                <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
                    <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
            </a-form-item>

            <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                <a-button size="large" type="primary" html-type="submit">发布</a-button>
            </a-form-item>
        </a-form>
    </div>
    
</template>

<script lang="ts">
export default {
    name: 'NewScript'
}
</script>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { UploadChangeParam, UploadProps, message } from 'ant-design-vue';
import { newTopic } from '@/api/forum_api'
 
interface FormState {
  topic:string,
  content:string,
}

const formState = reactive<FormState>({
    topic: '',
    content: '',
})
const fileList = ref<any[]>([]);
const picFiles = ref<any[]>([]);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const onFinish = async (values: any) => {
    console.log(picFiles)
    const formData = new FormData();
    formData.append("topic", formState.topic)
    formData.append("content", formState.topic)
    formData.append("picCount", picFiles.value.length.toString())
    for (let i = 0; i < picFiles.value.length; i++) {
        formData.append("pic"+i, picFiles.value[i])
    }
    await newTopic(formData)
    .then(resp => {
        message.info("新建成功")
    })
    .catch(err => {})
};
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview = async (file:any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};
const beforeUploadPic: UploadProps['beforeUpload'] = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG file!');
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        message.error('Image must smaller than 10MB!');
    }
    return isJpgOrPng && isLt10M;
};
const handleUpload = (info:any) => {
  picFiles.value.push(info.file)
  console.log(picFiles.value)
  fileList.value[fileList.value?.length-1].status = "done"
}
const handleRemove: UploadProps['onRemove'] = file => {
    let index = -1
    for (let i = 0, l = fileList.value.length; i < l; i++) {
        if (fileList.value[i].uid == file.uid) {
            index = i
        } 
    }
    fileList.value.splice(index, 1);
    let index2 = -1
    for (let i = 0, l = picFiles.value.length; i < l; i++) {
        if (picFiles.value[i].uid == file.uid) {
            index2 = i
        } 
    }
    picFiles.value.splice(index2, 1);
    console.log(picFiles.value)
};

</script>

